<?php

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2018/12/21
 * Time: 17:15
 */

namespace app\index\controller;

use think\validate\ValidateRule;

class Article extends Common
{

    /**
     * 查询文章
     * 文章状态[0：未审核、1：审核通过、2：审核失败、3：后台下架]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
       // $uid = $this->isCheckAuth();
        $uid = input('uid');
        $db = model('Article')->alias('a');
        $page = input('page') > 0 ? input('page/d') : 1;
        $listRows = input('listRows') > 0 ? input('listRows/d') : 30;
        $db->where('status', 1);
       // $files = 'a.id,title,a.images,a.content,a.abstract,id as commentCount,id as likesCount,id as shareCount';
        $files = 'a.id,title,a.images,a.content,a.abstract,a.status,a.updatetime,a.grade_status';
        $db->field($files)->order('a.top','asc')->order('a.starttime', 'desc')->page($page, $listRows);
        $data = $db->select();
        # 判断该用户是否点赞 点赞,分享,评论总数
        foreach($data as $k=>$v){
            $islike = db('collection')->where(['uid'=>$uid,'pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'like'])->find();
            if(!empty($islike)){ # 是否点赞
                $data[$k]['islike'] = 1;
            }else{
                $data[$k]['islike'] = 0;
            }
            if($v['grade_status']==2){   # 是否评级
                $data[$k]['israte'] = 1;
            }else{
                $data[$k]['israte'] = 0;
            }
            $isshare = db('collection')->where(['uid'=>$uid,'pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'share'])->find();
            if(!empty($isshare)){# 是否分享
                $data[$k]['isshare'] = 1;
            }else{
                $data[$k]['isshare'] = 0;
            }
            $wantbuy = db('collection')->where(['uid'=>$uid,'pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'wantbuy'])->find();
            if(!empty($wantbuy)){
                $data[$k]['wantbuy'] = 1;
            }else{
                $data[$k]['wantbuy'] = 0;
            }
            $fresh = db('collection')->where(['uid'=>$uid,'pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'fresh'])->find();
            if(!empty($fresh)){
                $data[$k]['fresh'] = 1;
            }else{
                $data[$k]['fresh'] = 0;
            }
            $likes = db('collection')->where(['pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'like'])->count();
            $data[$k]['likes']=$likes;
            $share = db('collection')->where(['pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'share'])->count();
            $data[$k]['share'] = $share;
            $wantbuys = db('collection')->where(['pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'wantbuy'])->count();
            $data[$k]['wantbuys'] = $wantbuys;
            $freshs = db('collection')->where(['pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'fresh'])->count();
            $data[$k]['freshs'] = $freshs;
            $comment = db('comment')->where(['pid'=>$v['id'],'modular'=>'article','status'=>0])->count();
            $data[$k]['comment'] = $comment;

        }
        $total = $db->count();
        $this->rest(['list' => $data, 'page' => getPage($page, $listRows, $total)]);
    }


    /**
     * 查询文章 列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function query()
    {
        $db = model('Article')->alias('a');
        $title = input('title');
        if ($title) {
            $db->where('title', 'like', "%$title%");
        }
        $db->where('status', 1);
        $categoriesId = input('categoriesId');
        if ($categoriesId) {
            $db->where('categories_id', $categoriesId);
        }
        $db->where('grade', '>', 0);
        $page = input('page') > 0 ? input('page/d') : 1;
        $listRows = input('listRows') > 0 ? input('listRows/d') : 10;
        $files = 'a.id,a.images,a.address,a.grade,a.score,a.words';
        $db->field($files)->page($page, $listRows)->order('a.updatetime', 'desc');
        $data = $db->select();
        $total = $db->count();
        $this->rest(['list' => $data, 'page' => getPage($page, $listRows, $total)]);
    }


    /**
     * 查看单个文章   aid: 文章id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function article()
    {
       // $this->isCheckAuth();
        $uid = input('uid');
        if(empty($uid)){
            $this->rest('参数错误', 's004');
        }
        $aid = trim(input('aid'));
        if(empty($aid)){
            $this->rest('查看失败','s004');
        }
        $sum = db('article')->where((['id'=>$aid]))->field('heat')->find();
        db('article')->where(['id'=>$aid])->update(['heat'=>$sum['heat']+1]);
        $db = model('Article')->alias('a');
        $files = 'id,uid,title,images,content,score,address,words,starttime,abstract,spotname';
        $res = $db->field($files)->where('id',$aid)->find();
        if(!empty($res)){
            $comment_db = db('comment')->alias('c');
            $files = 'c.id,c.content,c.like_time,u.id as uid,u.nickname,u.headurl';
            $com = $comment_db->field($files)->join('user u','c.uid=u.id','left')->where(['modular'=>1,'status'=>0,'c.aid'=>$res['id']])->select();
            if(!empty($com)){
                $res['comment'] = $com;
            }else{
                $res['comment'] = [];
            }
            $islike = db('collection')->where(['uid'=>$uid,'pid'=>$aid,'modular'=>'article','status'=>0,'type'=>'like'])->find();
            if(!empty($islike)){
                $res['islike'] = 1;
            }else{
                $res['islike'] = 0;
            }
            $isshare = db('collection')->where(['uid'=>$uid,'pid'=>$aid,'modular'=>'article','status'=>0,'type'=>'share'])->find();
            if(!empty($isshare)){
                $res['isshare'] = 1;
            }else{
                $res['isshare'] = 0;
            }
            $collection = db('collection')->where(['uid'=>$uid,'pid'=>$aid,'modular'=>'article','status'=>0,'type'=>'collection'])->find();
            if(!empty($collection)){
                $res['iscollection'] = 1;
            }else{
                $res['iscollection'] = 0;
            }
            $wantbuy = db('collection')->where(['uid'=>$uid,'pid'=>$aid,'modular'=>'article','status'=>0,'type'=>'wantbuy'])->find();
            if(!empty($wantbuy)){
                $res['wantbuy'] = 1;
            }else{
                $res['wantbuy'] = 0;
            }
            $fresh = db('collection')->where(['uid'=>$uid,'pid'=>$aid,'modular'=>'article','status'=>0,'type'=>'fresh'])->find();
            if(!empty($fresh)){
                $res['fresh'] = 1;
            }else{
                $res['fresh'] = 0;
            }

            $date = db('graded')->where('aid',$aid)->where('uid',$uid)->field('state')->find();
            $res['isLook'] = !empty($date)?$date['state']:false;
            $res['look'] = db('graded')->where('state',1)->count();
            $res['sign'] = db('graded')->where('state',2)->count();
        }
        $this->rest($res);
    }



    /**
     *   点赞   aid:   modular所属模块:[article：文章,line:线路]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function like()
    {
        //$uid = $this->isCheckAuth();
        $uid = input('uid');
        $aid = trim(input('aid'));
        $modular = input('modular');
        if(empty($uid) || empty($aid) || empty($modular)){
            $this->rest('参数错误', 's004');
        }
        $data = array(
            'uid' => $uid,
            'pid' => $aid,
            'type' => 'like',
            'modular' =>$modular,
        );
        $validate = validate('Collection');
        if (!$validate->check($data)) {
            $this->rest($validate->getError(), 's004');
        }
        $query = db('collection')->where(['uid'=>$uid,'pid'=>$aid,'type'=>'like','modular'=>$modular,'status'=>0])->find();
        if($query){
            $this->rest('已赞过','s004');
        }else{
            $rest = db('collection')->insert($data);
            if ($rest) {
                $this->rest('点赞成功');
            } else {
                $this->rest('点赞失败','s004');
            }
        }

    }

    /**
     * 添加 分享    modular所属模块:[article：文章,dynamic:旅说,line:线路]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function share()
    {
       // $uid = $this->isCheckAuth();
        $uid = input('uid');
        $aid = trim(input('aid'));
        $modular = input('modular');
        if (empty($uid) || empty($aid) || empty($modular)) {
            $this->rest('参数错误', 's004');
        }
        $data = array(
            'uid' => $uid,
            'pid' => $aid,
            'type' => 'share',
            'modular' => $modular,
        );
        $validate = validate('Collection');
        if (!$validate->check($data)) {
            $this->rest($validate->getError(), 's004');
        }
        $rest = db('collection')->insert($data);
        if ($rest) {
            $this->rest('分享成功');
        } else {
            $this->rest('分享失败','s004');
        }
    }

    /**
     * 收藏 [iscollection  1:收藏 2:取消收藏]   modular所属模块:[article：文章,line:线路]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function collection()
    {
        // $uid = $this->isCheckAuth();
        $uid = input('uid');
        $aid = trim(input('aid'));
        $iscollection = input('iscollection');
        $modular = input('modular');
        if (empty($uid) || empty($aid) || empty($iscollection || empty($modular))) {
            $this->rest('参数错误', 's004');
        }
        $data = array(
            'uid' => $uid,
            'pid' => $aid,
            'type' => 'collection',
            'modular' => $modular,
        );
        if ($iscollection == 1) {
            $validate = validate('Collection');
            if (!$validate->check($data)) {
                $this->rest($validate->getError(), 's004');
            }
            $query = db('collection')->where(['uid' => $uid, 'pid' => $aid, 'type' => 'collection', 'modular' => $modular])->find();
            if ($query) {
                if ($query['status'] == 1) {
                    $result = db('Collection')->where('id', $query['id'])->update(['status' => 0]);
                    if ($result) {
                        $this->rest('收藏成功');
                    } else {
                        $this->rest('收藏失败', 's004');
                    }
                } else {
                    $this->rest('已收藏,请勿重复收藏', 's004');
                }
            } else {
                $rest = db('collection')->insert($data);
                if ($rest) {
                    $this->rest('收藏成功');
                } else {
                    $this->rest('收藏失败', 's004');
                }
            }
        } else {
            $rest = db('Collection')->where($data)->update(['status' => 1]);
            if ($rest) {
                $this->rest('取消收藏成功');
            } else {
                $this->rest('取消收藏失败', 's004');
            }
        }
    }

    /*
     * 导航栏便利
     *
     * */
    public function navigation()
    {
        $list = db('article_categories')->field('id,name,icon')->select();
        $this->rest($list);
    }


    /*
     * 获取分类文章
     * */
    public function get_content()
    {
        $cid = input('type_id');
        $page = input('page') > 0 ? input('page/d') : 1;
        $listRows = input('listRows') > 0 ? input('listRows/d') : 10;
        $screen = empty(input('order')) ? 0 : input('order');
        $desc = empty(input('desc')) ? 'desc' : 'asc';
        $r_type = input('r_type');
        if (empty($cid)) $this->rest('参数错误','s004');
        $db = db('article')->alias('a')->join('grade g','a.grade_id=g.id','left');
        $field = 'a.id,a.title,a.images,a.address,a.words,a.abstract,a.uid,a.grade_status,a.score,a.look,a.grade_id,a.grade_status,g.icon';
        if (empty(input('rate'))){
            $sql = $db->where(['status'=>1,'categories_id'=>$cid])->field($field);
        }else{
            $sql = $db->where(['status'=>1,'categories_id'=>$cid,'grade_status'=>2])->where('grade_id','>',0)->field($field);
        }
        if ($cid == 7){
            if (empty($r_type)){
                $list = $sql->where(['status'=>1,'categories_id'=>$cid])->where('landmark','<>',0)->page($page,$listRows)->select();
            }else{
                $list = $sql->where(['status'=>1,'categories_id'=>$cid])->where('landmark',$r_type)->page($page,$listRows)->select();
            }
        }else{
            switch ($screen){
                case 0:
                    $list = $sql->page($page,$listRows)->select();
                    break;
                case 1:
                    $list = $sql->order('heat','desc')->page($page,$listRows)->select();
                    break;
                case 2:
                    $list = $sql->order('starttime',$desc)->page($page,$listRows)->select();
                    break;
                case 3:
                    $list = $sql->order('score','desc')->page($page,$listRows)->select();
                    break;
                case 4:
                    $list = $sql->page($page,$listRows)->select();
                    break;
                default:
                    $list = $sql->page($page,$listRows)->select();
                    break;
            }
        }

        if ($list){
            foreach ($list as $k=>$v){
                $list[$k]['score'] = $v['score'];
                $list[$k]['number'] = $v['look'];
                $list[$k]['images'] = json_decode($v['images']);
                $islike = db('collection')->where(['uid'=>$v['uid'],'pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'like'])->find();
                if(!empty($islike)){
                    $list[$k]['islike'] = 1;
                }else{
                    $list[$k]['islike'] = 0;
                }
                $isshare = db('collection')->where(['uid'=>$v['uid'],'pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'share'])->find();
                if(!empty($isshare)){
                    $list[$k]['isshare'] = 1;
                }else{
                    $list[$k]['isshare'] = 0;
                }
                if($v['grade_status']==2){   # 是否评级
                    $list[$k]['israte'] = 1;
                }else{
                    $list[$k]['israte'] = 0;
                }
                $list[$k]['likes'] = db('collection')->where(['pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'like'])->count();
                $list[$k]['share'] = db('collection')->where(['pid'=>$v['id'],'modular'=>'article','status'=>0,'type'=>'share'])->count();
                $list[$k]['comment'] = db('comment')->where(['aid'=>$v['id'],'modular'=>1,'status'=>0])->count();
                unset($v['uid']);
            }
            $total = $db->count();
            $this->rest(['list' => $list, 'page' => getPage($page, $listRows, $total)]);
        }else{
            $this->rest($list);
        }
    }



    /*
     * 文章签到 【到此一游】
     * */
    public function sign()
    {
        if (empty(input('uid')) || empty(input('aid')) || empty(input('score')) || empty(input('state'))){
            $this->rest('参数错误','s004');
        }
        $db = db('graded');
        $data = [
            'uid' => input('uid'),
            'aid' => input('aid'),
            'score' => input('score'),
            'c_time' => time(),
            'modular' => 1,
            'state' => input('state'),
        ];

        $date = db('graded')->where('aid',$data['aid'])->where(['modular' => 1,'uid' => $data['uid']])->field('state')->find();
        if ($date['state'] == 2){
            $this->rest('该景点您已签到过了，欢迎再次光临','s004');
        }
        if ($data['state'] == 1 && $date['state'] == 1){
            db('graded')->where('state',1)->where('aid',$data['aid'])->where('uid',$data['uid'])->delete();
            $lists['look'] = db('graded')->where('state',1)->count();
            $lists['sign'] = db('graded')->where('state',2)->count();
            $this->rest($lists);
        }
        if (empty($date)){
            $list = $db->insert($data);
            if ($list){
                $sum['score'] = db('graded')->where(['modular' => 1,'state'=>2])->avg('score');
                $sum['look'] = db('graded')->where(['modular' => 1])->count();
                db('article')->where('id',$data['aid'])->update($sum);
                $lists['look'] = db('graded')->where(['modular' => 1,'state'=>1])->count();
                $lists['sign'] = db('graded')->where(['modular' => 1,'state'=>2])->count();
                $lists['message'] = '签到成功';
                $this->rest($lists);
            }else{
                $this->rest('签到失败，请稍后再试','s0004');
            }
        }

    }


    /**
     * 获取文章评论内容
     * modular1文章2旅说
     */
    public function get_comment()
    {
        $aid = input('aid');
        $uid = input('uid');
        $page = empty(input('page')) ? 1 : input('page');
        $modular = input('modular');
        if (empty($aid) || empty($uid) || empty($modular)) $this->rest('参数错误','s004');
        $comment_db = db('comment')->alias('c');
        $files = 'c.id,c.aid,c.uid,c.pid,c.content,c.like_time,c.number,u.nickname,u.headurl';
        $com = $comment_db->field($files)->join('user u','c.uid=u.id','left')->where(['c.modular'=>$modular,'c.status'=>0,'c.aid'=>$aid])->page($page,10)->select();
        $nums = count($com);
        if ($nums>0) {
            $data = $this->arr_to_tree($com,$uid);
            $total = db('comment')->where(['modular'=>$modular,'status'=>0,'aid'=>$aid])->count();
            $this->rest(['list' => $data, 'page' => getPage($page, 10, $total)]);
        }else{
            $this->rest([]);
        }
    }

    /*
     * 递归遍历
     *
     * */
    public function arr_to_tree($list,$uid=0,$root=0,$pk='id',$pid='pid',$child='child')
    {
        $tree=array();
        foreach($list as $key=> $val){
            $val['is_like'] = is_u_like($val['id'],$uid);
            if($val[$pid]==$root){
                //获取当前$pid所有子类
                unset($list[$key]);
                if(!empty($list)){
                    $childArr=$this->arr_to_tree($list,$uid,$val[$pk],$pk,$pid,$child);
                    if(!empty($childArr)){
                        $val[$child]=$childArr;
                    }
                }
                $tree[]=$val;
            }
        }
        return $tree;
    }

    /**
     * 发布评论   modular1文章2旅说
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function article_commentAdd()
    {
        //$uid = $this->isCheckAuth();
        $uid = input('uid');
        $modular = input('modular');
        $pid = empty(input('pid')) ? 0 : input('pid');
        if (empty($uid) || empty(input('aid')) || empty(input('content')) || empty(input('modular'))) {
            $this->rest('参数错误','s004');
        }
        if (empty(trim_str(input('content')))) $this->rest('内容为空或空字符','s004');
        $data = array(
            'uid' => $uid,
            'pid' => $pid,
            'aid' => trim(input('aid')),
            'modular' => $modular,
            'content' => trim(input('content')),
            'status'  => 0,
            'number'  => 0,
            'like_time' => time(),
        );
        $rest = db('comment')->insert($data);
        if ($rest) {
            $this->rest('评论成功');
        } else {
            $this->rest('评论失败','s004');
        }
    }

    /**
     * 删除评论    modular1文章2旅说
     */
    public function del_comment()
    {
        $uid = input('uid');
        $id = input('id');
        $aid = input('aid');
        $modular = input('modular');
        if (empty($id) || empty($uid) || empty($modular) || empty($aid)) {
            $this->rest('参数错误', 's004');
        }
        $rest = db('comment')->where('modular', $modular)->where(['id|pid'=>$id,'aid'=>$aid])->delete();
        if ($rest) {
            $this->rest('删除成功');
        } else {
            $this->rest('删除失败','s004');
        }
    }

    /*
     * 递归删除
     *
     * */
    function ids($list,$root=0,$pk='uid',$pid='pid')
    {
        $ids=array();
        foreach($list as $key=> $val){
            if($val[$pid]==$root){
                //获取当前$pid所有子类
                $ids[]=$val[$pk];
                unset($list[$key]);
                if(!empty($list)){
                    $ids = array_merge($ids,$this->ids($list,$val[$pk],$pk,$pid));
                }
            }
        }
        return $ids;
    }
}
